<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 优惠券购买领取接口
 */
namespace app\allwin\controller\api\v4;
use app\allwin\controller\api\Base;
use app\allwin\model\Bank;
use app\allwin\model\BankBill;
use app\allwin\model\CouponUser;
use app\allwin\model\CouponOrder;
use app\common\facade\WechatPay;
use Exception;

class couponNotify extends Base{
   
    /**
     * 付费领取优惠券
     */
    public function index(){
        try{
            $response = WechatPay::doPay($this->miniapp_id)->handlePaidNotify(function ($message,$fail) {
                $result = CouponOrder::where(['state'=>0,'order_no' => $message['out_trade_no']])->find();
                if (empty($result)) {
                    return true;
                }
                if ($message['return_code'] === 'SUCCESS') {
                    if ($message['result_code'] === 'SUCCESS') {
                        $sub_mchid  = $message['sub_mch_id'] ?? '';
                        $ispay = WechatPay::doPay($this->miniapp_id,false,$sub_mchid)->order->queryByOutTradeNumber($result->order_no);
                        if ($ispay['return_code'] === 'SUCCESS') {
                            if ($ispay['result_code'] === 'SUCCESS') {
                                if ($ispay['trade_state'] === 'SUCCESS') {
                                    $result->state     = 1;
                                    $result->paid_time = strtotime($ispay['time_end']);;
                                    $result->paid_no   = $ispay['transaction_id'];
                                    $result->save();
                                    CouponUser::addUserCoupon($result->coupon_ids,$result->user_id); //领取的优惠券入库
                                    //增加日志
                                    BankBill::add(['miniapp_id'=>$this->miniapp_id,'store_id' => 0,'money' => -$result->amount,'uid'=>$result->user_id,'pay_uid' => $result->user_id], '微信支付[领取优惠券]');
                                    //开通收益计算
                                    Bank::rePoints($this->miniapp_id, $result->user_id,intval($result->amount));   //增加积分
                                    return true;
                                }
                            }
                        }
                    }
                }
                return $fail('通信失败,请稍后再通知我');
            });
            $response->send();
        }catch (Exception $e) {
            $this->error('页面不存在');
        }
    }
}